<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Product_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 根据学校和日期返回菜谱数量(学校某天是否订餐)
	 */
	public function count_by_school_date_type($schoolid,$date,$type){
		$this->db->where('schoolid',$schoolid);
		$this->db->where('date',$date);
		if($type!=-1){
			$this->db->where('type',$type);
		}
		$num = $this->db->count_all_results('t_cookbook');
		return $num;
	}
	/*
	 *根据学校和日期返回商品信息(返回学校当天的商品列表)
	 */
	public function find_by_school_date($schoolid,$date){
		$this->db->select('t_cookbook.type,t_cookbook.daylim,t_cookbook.stock,t_product.id,t_product.name,t_product.image,t_product.description,t_product.price,t_product.unit');
		$this->db->from('t_cookbook');
		$this->db->join('t_product', 't_cookbook.productid = t_product.id','left');
		$this->db->where('schoolid',$schoolid);
		$this->db->where('date',$date);
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 根据商品ID得到商品信息
	 */
	public function load($id){//
		if (!$id){
			return array();
		}
		$this->db->where('id',$id);
		$query = $this->db->get('t_product');
		if ($row = $query->row_array()){
			return $row;
		}
		return array();
	}
	/*
	 *根据学校，日期，商品和三餐类型返回商品信息(用于判断商品库存)
	 */
	public function find_by_school_date_product_type($schoolid,$date,$productid,$type){
		$this->db->select('t_cookbook.stock,t_product.name');
		$this->db->from('t_cookbook');
		$this->db->join('t_product', 't_cookbook.productid = t_product.id','left');
		$this->db->where('schoolid',$schoolid);
		$this->db->where('date',$date);
		$this->db->where('productid',$productid);
		$this->db->where('type',$type);
		$query = $this->db->get();
		return $query->row_array();
	}
	/*
	 * 根据分类ID得到商品信息(用于获取默认餐)
	 */
	public function find_by_category($categoryid){
		$this->db->where('categoryid',$categoryid);
		$query = $this->db->get('t_product');
		return $query->row_array();
	}
	/*
	 * 减少商品库存
	 */
	public function updateStock($schoolid,$date,$productid,$type,$amount){
		$sql="update t_cookbook set stock=stock-".$amount." where schoolid=".$schoolid." and date='".$date. "' and productid=".$productid. " and type=".$type;
		$this->db->query($sql);
		return $this->db->affected_rows()>0;
	}
	/*
	 * 增加商品库存
	 */
	public function updateStock2($schoolid,$date,$productid,$type,$amount){
		$sql="update t_cookbook set stock=stock+".$amount." where schoolid=".$schoolid." and date='".$date. "' and productid=".$productid. " and type=".$type;
		$this->db->query($sql);
		return $this->db->affected_rows()>0;
	}
}